package com.cms.admin.action.privilege;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.aliyun.oss.model.PutObjectResult;
import net.sf.json.JSONObject;

import com.cms.admin.action.BaseAction;
import com.cms.admin.model.DepartmentList;
import com.cms.admin.model.FuncList;
import com.cms.admin.model.City;
import com.cms.admin.model.PageBean;
import com.cms.admin.model.UserRole;
import com.cms.admin.model.UserList;
import com.cms.admin.model.UserListExt;
import com.cms.admin.service.common.FuncListService;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.employee.DepartmentListService;
import com.cms.admin.service.privilege.CityService;
import com.cms.admin.service.privilege.UserRoleService;
import com.cms.admin.service.privilege.UserListService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.MD5Password;
import com.opensymphony.xwork2.ModelDriven;

public class UserManagerAction extends BaseAction implements
		ModelDriven<UserListExt> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private UserListService userListService;
	private UserRoleService userRoleService;
	private CityService cityService;
	private TemplateService templateService;
	private List<UserList> userList;
	private List<UserRole> roleList;

	private UserList user;


	//href传入的用户Id
	private String userid;

	private UserListExt search = new UserListExt();
	private PageBean page;
	private String res;


	//用户老密码
	private String oldPassword;

	//用户输入的老密码
	private String oldPassword2;
	//用户重复的用户新密码
	private String password2;
	private DepartmentListService departmentService;
	private List<DepartmentList> departmentList;
	private FuncListService funcListService;
	//菜单树
	List<FuncList>  subMenuTree =null;
	
	private UserList detailUser;

	public String ajaxQueryUser() {
		try {
			 
			LOG.info("Start ArticleAction process,method is ajaxQuery");
			LOG.debug("Action is:" + search.getAction());
			page = new PageBean(search.getCurrentPage(), search.getPageSize());
			//仅查询用户
			search.setTypeid(1);
			userList = userListService.getAllUser(page, search);
			subMenuTree =funcListService.getAllSubMenu();
			
			String res = this.getQueryResult(userList, page,subMenuTree);
			JSONObject o = new JSONObject();
			o.put("pageCount", page.getTotalPage());
			o.put("content", res);
			return ajaxJsonSuccessMessage(o);
        
		} catch (Exception e) {

			e.printStackTrace();
			return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
		}

	}

	public String ajaxQueryUserDetail()
	{
		initBathPath();
		detailUser=userListService.getById(search.getUserid());
		if (null!=detailUser)
		{
			return SUCCESS;
		}

		return null;

	}

	public String ajaxUpdateUser()
	{
		initBathPath();
		if (null!=search.getIconImage())
		{
			String icoUrl=uploadUserIcon(search.getIconImage(),search.getIconImageFileName(),search.getUserid());
			search.setIconUrl(icoUrl);
		}
		userListService.updateSelfInfoById(search);
		return SUCCESS;
	}

	/**
	 * 更新用户信息
	 * */
	private String getQueryResult(List<UserList> userList, PageBean page,List<FuncList> subMenuTree)
			throws Exception {
		initBathPath();
		HashMap map = new HashMap();
		map.put("userList", userList);
		map.put("page", page);
		map.put("basePath", getBasePath());
		map.put("subMenuTree", subMenuTree);
		  
		String result = "";
		result = templateService.generateContentByFreeMarker(
				Constants.TEMPLATE_USER_QUERY_RESULT, map);
		return result;
	}

	private void parseUserResourceLable(List<UserList> userList) {

		for (UserList u : userList) {

		}

	}

	public String queryUserList() {

		try {

			page = new PageBean(search.getCurrentPage(), search.getPageSize());
			userList = userListService.getAllUser(page, search);
			roleList = userRoleService.getAllRole();
			subMenuTree =funcListService.getAllSubMenu();

			parseUserResourceLable(userList);

			res = getQueryResult(userList, page,subMenuTree);
	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res=Constants.INFO_SYS_ERROR;
			return ERROR;
		}

		return SUCCESS;

	}

	public String preAddUser() {

		roleList = userRoleService.getAllRole();
 
 
		departmentList = departmentService.getAllRows();
		
		subMenuTree =funcListService.getAllSubMenu();
		
		return SUCCESS;
	}

	public String addUser() {
		
		//LOG.debug("org:" + user.getOrg());
		//LOG.debug("role id:" + user.getRoleId());
		//??У???????????
		
		UserList tempUser = userListService.getByName(user.getUserName());
		
		if(null!=tempUser)
		{
			
			res="???????("+tempUser.getUserName()+")???????????????????????????????";
			return ERROR;
			
		}
		 
		
		//?????????
		user.setPassword(MD5Password.getEncodedPassword_Hex(user.getPassword()));
		userListService.insertUser(user);

		return SUCCESS;
	}

	public String getUserById() {
		preAddUser();
		LOG.debug(userid);
		
		Integer key =null;
		if(null!=userid)
		{
			key=Integer.valueOf(userid);
		}
		user = userListService.getById(key);

		departmentList = departmentService.getAllRows();
		
		subMenuTree =funcListService.getAllSubMenu();
		LOG.debug("??????:" + user.toString());

		return SUCCESS;
	}


	public String getSelfInfo()
	{
		UserList userSeesion = (UserList) this.att.get(Constants.USER_OBJECT);
		
		user = userListService.getById(userSeesion.getUserid());
		
		List<UserList> tempUserList = new ArrayList<UserList>();
		
		tempUserList.add(user);

		parseUserResourceLable(tempUserList);
		
		user=tempUserList.get(0);
		
		return SUCCESS;
		
	}
	
	public String updateUserById() {

		LOG.debug("??????:" + user.toString());

		userListService.updateUser(user);

		return SUCCESS;

	}

	public String updateSelfInfoById()
	{

		user.setPassword(MD5Password.getEncodedPassword_Hex(user.getPassword()));
		userListService.updateSelfInfoById(user);
	
		return SUCCESS;
		
	}
	
	public String preChangeSelfPassword()
	{
		preAddUser();
		
		user = (UserList) this.att.get("userInfo");
		
		return SUCCESS;
	}
	
	
	public String updateSelfPassword()
	{
		
		
		if(null!=user && null!=user.getPassword())
		{
			 
			
			this.res= MD5Password.getEncodedPassword_Hex(this.res);
			if(this.oldPassword2.equals(this.res))
			{
				if(user.getPassword().equals(this.password2))
				{
					user.setPassword(MD5Password.getEncodedPassword_Hex(user.getPassword()));
					userListService.updateSelfPassword(user);
				}
				else
				{
					res="??????????????β?????";
					return ERROR;
				}
			}
			else
			{
				res="?????????????";
				return ERROR;
			}
		}
	
		return SUCCESS;
	}
	
	public String resetUserPassword()
	{
		UserList user = new UserList();
		int key = 0;
		if(null!=userid)
		{
			key=Integer.valueOf(userid);
			
		}
		 
		
		//LOG.debug("????????:"+user.getUserId());
		UserList newUser = userListService.getById(key);
		//??????????
		String newPD=newUser.getUserName()+"123456";
		//LOG.info("newPD:"+newPD);
		
		//?????????
		String newEncodeedPD=MD5Password.getEncodedPassword_Hex(newPD);
		//LOG.info("newEncodeedPD:"+newEncodeedPD);
		
		user.setPassword(newEncodeedPD);
		//user.setUserId(newUser.getUserId());
		userListService.resetUserPassword(user);
		return SUCCESS;
		
	}
 

	public String deleteUserById() {

		userListService.deleteUser(userid);

		return SUCCESS;
	}
 
	@Override
	public UserListExt getModel() {
		// TODO Auto-generated method stub
		return search;
	}

	public UserListService getUserListService() {
		return userListService;
	}

	public void setUserListService(UserListService userListService) {
		this.userListService = userListService;
	}

	public UserRoleService getUserRoleService() {
		return userRoleService;
	}

	public void setUserRoleService(UserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}

	public CityService getCityService() {
		return cityService;
	}

	public void setCityService(CityService cityService) {
		this.cityService = cityService;
	}

	public TemplateService getTemplateService() {
		return templateService;
	}

	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}

	public DepartmentListService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentListService departmentService) {
		this.departmentService = departmentService;
	}

	public FuncListService getFuncListService() {
		return funcListService;
	}

	public void setFuncListService(FuncListService funcListService) {
		this.funcListService = funcListService;
	}

	public UserList getDetailUser() {
		return detailUser;
	}

	public void setDetailUser(UserList detailUser) {
		this.detailUser = detailUser;
	}


	private String uploadUserIcon(File img,String fileName,Long userId)
	{
		//后缀
		try {
			String tailSuffix = getExtension(fileName);
			String DIR="user/"+userId.longValue()+"/ico/"+System.currentTimeMillis()+tailSuffix;
			PutObjectResult result=uploadByOss(img,DIR);
			if (null!=result)
			{
				return DIR;
			}else
			{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}

}
